package org.mparts.server.utils;

import java.util.Collections;

//import org.apache.log4j.Logger;

import java.util.logging.Logger;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheFactory;
import net.sf.jsr107cache.CacheManager;

public final class CacheUtils {
	
	private static Logger log = Logger.getLogger(CacheUtils.class.getName());
//	private static Logger log = Logger.getLogger(CacheUtils.class);
	
	private static Cache cache;
	
	public static final String NEWS_LIST_KEY = "news_list";
	public static final String GROUPS_LIST_KEY = "grp_list";
	public static final String AUTO_LIST_KEY = "auto_list";
	public static final String ENGINE_LIST_KEY = "engine_list";
	
	static {
		try {
			CacheFactory cacheFactory = CacheManager.getInstance()
					.getCacheFactory();
			cache = cacheFactory.createCache(Collections.emptyMap());
			log.warning("Cache created");
		} catch (CacheException e) {
			log.severe("Failed cache creation");
//			log.error("Failed cache creation", e);
		}
	}
	
	private CacheUtils() {
		
	}
	
	
	public static void setCacheData( Object key, Object value ) {
		if ( cache != null ) {
			cache.put(key, value);
		} else {
			log.warning("Cache is null. It is not possible to store item");
//			log.warn("Cache is null. It is not possible to store item");
		}
	}
	
	public static Object getCacheData(Object key) {
		Object value = null;
		if ( cache != null ) {
			if ( cache.containsKey(key) ) {
				value = cache.get(key);
			} else {
				log.warning("No key " + key +" in cache");
			}
		} else {
			log.warning("Cache is null. It is not possible to get item");
//			log.warn("Cache is null. It is not possible to get item");
		}
		
		return value;
	}
	
	public static void removeCacheData(Object key) {
		if ( cache != null && cache.containsKey(key)) {
			cache.remove(key);
		} else {
			log.warning("Cache is null. It is not possible to remove item");
//			log.warn("Cache is null. It is not possible to remove item");
		}
	}

	public static void removeAll() {
		if ( cache != null && cache.size() > 0 ) {
			cache.clear();
		} else {
			log.warning("Cache is null. It is not possible to remove item");
//			log.warn("Cache is null. It is not possible to remove item");
		}
	}

}
